package com.wosai.teach.view;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lidroid.xutils.BitmapUtils;
import com.wosai.teach.R;
import com.wosai.teach.adapter.NewPagerAdapter;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.FixedSpeedScroller;
import com.wosai.teach.utils.OtherUtils;

/**
 * @author qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015年8月7日 下午3:50:16
 * @desc : 轮播图片处理
 */
public class BannerView extends LinearLayout {

	private BannerRunnable runnable;

	private ViewPager vp;

	private ViewGroup vg;

	private NewPagerAdapter adapter;

	private FixedSpeedScroller scroller;

	private List<ImageView> pointList;

	private BitmapUtils bitmapUtils;

	private boolean run = false;

	public BannerView(Context context) {
		super(context);
	}

	public BannerView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void initAttribute(BitmapUtils bitmapUtils) {
		this.vg = (ViewGroup) this.findViewById(R.id.banner_vg);
		this.vp = (ViewPager) this.findViewById(R.id.banner_vp);
		this.bitmapUtils = bitmapUtils;
		pointList = new ArrayList<ImageView>();
		List<View> viewList = new ArrayList<View>();
		runnable = new BannerRunnable("BannerView");
		adapter = new NewPagerAdapter(viewList);
		vp.setAdapter(adapter);
		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				if (OtherUtils.CheckNull(pointList)) {
					return;
				}
				for (int i = 0; i < pointList.size(); i++) {
					pointList.get(i).setSelected(false);
				}
				pointList.get(index).setSelected(true);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		try {
			Field mField = ViewPager.class.getDeclaredField("mScroller");
			mField.setAccessible(true);
			scroller = new FixedSpeedScroller(getContext(),
					new AccelerateInterpolator());
			mField.set(vp, scroller);
			scroller.setmDuration(500);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addImages(String[] images) {
		if (OtherUtils.CheckNull(images)) {
			return;
		}
		List<View> viewList = new ArrayList<View>();
		LayoutInflater layIn = LayoutInflater.from(getContext());
		boolean firstPoint = true;
		for (String url : images) {
			if (OtherUtils.CheckNull(url)) {
				continue;
			}
			View view = layIn.inflate(R.layout.activity_lun_item, vp, false);
			ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
			bitmapUtils.display(iv, url);
			viewList.add(view);
			addPoint(firstPoint);
			firstPoint = false;
		}
		adapter.addList(viewList);
		startFlow();
	}

	public void addViews(Integer[] layoutId, boolean start) {
		if (OtherUtils.CheckNull(layoutId)) {
			return;
		}
		boolean firstPoint = true;
		List<View> viewList = new ArrayList<View>();
		LayoutInflater layIn = LayoutInflater.from(getContext());
		for (int id : layoutId) {
			if (OtherUtils.CheckNull(id)) {
				continue;
			}
			View view = layIn.inflate(id, vp, false);
			viewList.add(view);
			addPoint(firstPoint);
			firstPoint = false;
		}
		adapter.addList(viewList);

		if (start) {
			startFlow();
		}
	}

	public void addImages(Integer[] resIds) {
		if (OtherUtils.CheckNull(resIds)) {
			return;
		}
		boolean firstPoint = true;
		List<View> viewList = new ArrayList<View>();
		LayoutInflater layIn = LayoutInflater.from(getContext());
		for (int resId : resIds) {
			if (OtherUtils.CheckNull(resId)) {
				continue;
			}
			View view = layIn.inflate(R.layout.activity_lun_item, vp, false);
			ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
			iv.setImageResource(resId);
			viewList.add(view);
			addPoint(firstPoint);
			firstPoint = false;
		}
		startFlow();
	}

	public View getView(int index) {
		if (adapter == null) {
			return null;
		}
		List<View> viewList = adapter.getViewList();
		if (OtherUtils.CheckNull(viewList)) {
			return null;
		}
		return viewList.get(index);
	}

	public void addPoint(boolean firstPoint) {
		int dp9 = AppUtil.dip2px(getContext(), 9);
		ImageView point = new ImageView(getContext());
		LayoutParams lp = new LayoutParams(dp9, dp9);
		lp.setMargins(dp9 / 3, 0, dp9 / 3, 0);
		point.setLayoutParams(lp);
		point.setImageResource(R.drawable.dian_select);
		if (firstPoint) {
			point.setSelected(true);
		}
		vg.addView(point);
		pointList.add(point);
	}

	public void stopFlow() {
		this.run = false;
	}

	public void startFlow() {
		if (!this.run) {
			this.run = true;
			new Thread(runnable).start();
		}
	}

	private final int SHOW_NEXT = 0011;
	public boolean showNext = true;

	class BannerRunnable implements Runnable {

		private String threadName;

		public BannerRunnable(String name) {
			this.threadName = name;
		}

		@Override
		public void run() {
			System.out.println("BannerRunnable||" + this.threadName + "||"
					+ this.getClass());
			while (run) {
				try {
					Message msg = new Message();
					msg.what = SHOW_NEXT;
					mHandler.sendMessage(msg);
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_NEXT:
				if (showNext) {
					// 从右向左滑动
					showNextView();
				} else {
					// 从左向右滑动
					showPreviousView();
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	// 向左滑动
	public void showNextView() {
		// ++
		int count = vp.getAdapter().getCount();
		if (count > 1) { // 多于1个，才循环
			int index = vp.getCurrentItem();
			index = (index + 1) % count;
			vp.setCurrentItem(index, true);
		}
	}

	// 向右滑动
	public void showPreviousView() {
		// --
		int count = vp.getAdapter().getCount();
		if (count > 1) { // 多于1个，才循环
			int index = vp.getCurrentItem();
			index = (index - 1) % count;
			if (index == -1) {
				index = count - 1;
			}
			vp.setCurrentItem(index, true);
		}
	}
}
